package cn.com.jinhao.provider.user.service.impl;

import cn.com.jinhao.hotline.commons.vo.user.LoginRequestVo;
import cn.com.jinhao.provider.user.entity.User;
import cn.com.jinhao.provider.user.mapper.CommonMapper;
import cn.com.jinhao.provider.user.mapper.UserMapper;
import cn.com.jinhao.provider.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;


/**
 * hotline-spring-cloud
 * <p>Description: </p>
 *
 * @author ShaneMew
 * @version 1.0
 * @date 2019/12/17
 * @since 2019-12-17
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private CommonMapper commonMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User queryByCode(String userCode) {
            User user = new User();
            user.setCode(userCode);
            user = userMapper.selectOne(user);
            return user;
    }

    @Override
    public boolean add(User user) {
            String code = commonMapper.getCode("ST$OPER");
            user.setCode(StringUtils.isBlank(code) ? "0" : String.valueOf(Integer.parseInt(code) + 1));
            userMapper.insertSelective(user);
            return true;
    }

    @Override
    public boolean update(User user) {
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code", user.getCode());
            userMapper.updateByExample(user, example);
            return true;
    }

    @Override
    public User login(LoginRequestVo loginRequestVo) {
            //TODO: 暂时采用原始版本用code登录，后期需要改为用name登录
            User user = new User();
            user.setCode(loginRequestVo.getUsername());
            return userMapper.selectOne(user);
    }

    @Override
    public boolean delete(String code) {
            Example example = new Example(User.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code", code);
            userMapper.deleteByExample(example);
            return true;
    }

    @Override
    public String getNameByCode(String code) {
            return userMapper.getNameByCode(code);
    }
}
